package cn.xx.auth.controller;

import cn.xx.auth.comm.SuperController;
import cn.xx.auth.entity.User;
import cn.xx.auth.util.RandomUtil;
import cn.xx.auth.vo.Result;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController extends SuperController {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @PostMapping("/login")
    @ResponseBody
    public String login(
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "password", required = false) String password
    ) {
        String errorMsg = "用户名或密码错误";
        //校验用户是否存在
        //校验密码
        String token = "token-" + RandomUtil.getCharacterAndNumber(8);
//        session.setAttribute(token, true);
//        session.invalidate();
//        session.setAttribute(session.getId(), new User("1", "1", "1"));
        Cookie cookie = new Cookie("authToken", token);
        cookie.setMaxAge(3);
        response.addCookie(cookie);

        //存redis并设置过期时间
//        redisTemplate.opsForValue().set(session.getId(), new User("1", "zhangsan", "123456"),30, TimeUnit.MINUTES);

        redisTemplate.opsForHash().put(token,"id","1");
        redisTemplate.opsForHash().put(token,"uname","zhangsan");
        redisTemplate.opsForHash().put(token,"upass","123456");
        try {
            response.sendRedirect("/index.html");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @PostMapping("logout")
    public Result<?> logout(HttpServletRequest request, HttpServletResponse response) {
        if (request.getCookies() == null) {
            return Result.ok();
        }
        for (Cookie cookie : request.getCookies()) {
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            //删除redis里的值
            if (redisTemplate.opsForValue().get(cookie.getValue()) != null) {
                redisTemplate.delete(cookie.getValue());
            }

        }

        return Result.ok();
    }
}
